package com.wva.video.service.impl;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wva.common.client.UserClient;
import com.wva.common.context.UserContext;
import com.wva.common.domain.dto.PageQueryDTO;
import com.wva.common.domain.vo.PageQueryVO;
import com.wva.video.domain.dto.VideoProcessDTO;
import com.wva.video.domain.dto.VideoSubmissionDTO;
import com.wva.video.domain.po.Video;
import com.wva.video.domain.po.VideoWithMetadata;
import com.wva.video.domain.vo.VideoItemDTO;
import com.wva.video.domain.vo.VideoVO;
import com.wva.video.enums.QueueEnum;
import com.wva.video.enums.VideoStatus;
import com.wva.video.mapper.VideoMapper;
import com.wva.video.service.VideoCoverService;
import com.wva.video.service.VideoService;
import com.wva.video.service.VideoTagService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hong
 * @since 2025-02-17
 */
@Service
@Slf4j
public class VideoServiceImpl extends ServiceImpl<VideoMapper, Video> implements VideoService {
    @Autowired
    RabbitTemplate rabbitTemplate;
    @Autowired
    VideoTagService videoTagService;
    @Autowired
    VideoMapper videoMapper;
    @Resource
    UserClient userClient;
    @Resource
    VideoCoverService videoCoverService;


    @Override
    @Transactional
    public void submission(VideoSubmissionDTO videoSubmissionDTO) {
        //新增稿件
        Video video = BeanUtil.copyProperties(videoSubmissionDTO, Video.class);
        video.setUserId(UserContext.getUserId());
        video.setStatus(VideoStatus.WAIT_PRE_PROCESS.getStatus());
        save(video);

        //设置标签
        videoTagService.setVideoTags(video.getId(), videoSubmissionDTO.getTags());

        //推送稿件到预处理队列
        VideoProcessDTO videoProcessDTO = new VideoProcessDTO();
        videoProcessDTO.setVideoId(video.getId());
        videoProcessDTO.setFileMd5(videoSubmissionDTO.getFileMd5());
        videoProcessDTO.setTags(videoSubmissionDTO.getTags());
        rabbitTemplate.convertAndSend(
                QueueEnum.VIDEO_PROCESS_PRE.getExchange(),
                QueueEnum.VIDEO_PROCESS_PRE.getRoutingKey(),
                videoProcessDTO
        );
    }

    @Override
    public void markVideoTagsUpdate(Long videoId) {
        updateById(
                Video.builder()
                        .id(videoId)
                        .tagsUpdateTime(LocalDateTime.now())
                        .build()
        );
    }

    @Override
    public VideoVO getPublicWorkById(Long videoId) {
        //从数据库读取
        VideoWithMetadata videoWithMetadata = videoMapper.getWithMetadataById(videoId);
        if (videoWithMetadata == null) return null;

        //videoWithMetadata封装到VideoItemVO
        VideoVO videoVO = new VideoVO();
        BeanUtil.copyProperties(videoWithMetadata.getVideo(), videoVO);
        BeanUtil.copyProperties(videoWithMetadata.getVideoMetadata(), videoVO);
        return videoVO;
    }

    @Override
    public void wrapVideoItemDTOList(List<VideoItemDTO> videoItemDTOS) {
        //设置封面链接
        for (VideoItemDTO videoItemDTO : videoItemDTOS) {
            videoCoverService.wrapVideoItemVOWithCoverUrl(videoItemDTO);
        }

        //调用用户微服务获取昵称集合
        List<Long> authorUserIds = videoItemDTOS.stream().map(VideoItemDTO::getUserId)
                .collect(Collectors.toList());
        Map<Long, String> nicknames = userClient.getNicknamesByIds(authorUserIds);

        //将昵称封装到响应VO中
        for (VideoItemDTO videoItemDTO : videoItemDTOS) {
            videoItemDTO.setUserNickname(
                    nicknames.get(videoItemDTO.getUserId())
            );
        }
    }

    @Override
    public PageQueryVO<VideoItemDTO> listUserPublishVideo(Long userId, PageQueryDTO pageQueryDTO) {
        //分页条件
        Page<Video> page = Page.of(pageQueryDTO.getPageNo(), pageQueryDTO.getPageSize());
        page.addOrder(pageQueryDTO.getDesc() ? OrderItem.desc(pageQueryDTO.getSortBy()) : OrderItem.asc(pageQueryDTO.getSortBy()));

        //分页查询
        Page<Video> pages = lambdaQuery()
                .eq(Video::getStatus, VideoStatus.NORMAL.getStatus()) //必须是正常状态的
                .eq(Video::getUserId, userId) //必须是此用户发布的
                .page(page);//分页条件

        //类型转换
        List<VideoItemDTO> videoItemDTOS = pages.getRecords().stream().map(video -> BeanUtil.copyProperties(video, VideoItemDTO.class))
                .collect(Collectors.toList());

        //包装视频条目列表
        wrapVideoItemDTOList(videoItemDTOS);

        //封装到PageQueryVO
        PageQueryVO<VideoItemDTO> pageQueryVO = new PageQueryVO<>();
        pageQueryVO.setTotal(pages.getTotal());
        pageQueryVO.setPages(pages.getPages());
        pageQueryVO.setList(videoItemDTOS);
        return pageQueryVO;
    }
}
